package com.mfoyou.agent.web.controller.others;

import com.alibaba.fastjson.JSON;
import com.mfoyou.agent.web.intercepter.UrlRight;
import com.mfoyou.agent.web.intercepter.UserRight;
import com.mfoyou.agent.web.service.account.AccountService;
import com.mfoyou.agent.web.service.session.SessionService;
import com.mfoyou.agent.web.service.thirdPart.YouzanService;
import com.mfoyou.agent.web.utils.redis.RedisCacheManger;
import org.mfoyou.agent.common.dao.domain.HuawuUser;
import org.mfoyou.agent.common.dao.domain.HuawuYouzan;
import org.mfoyou.agent.utils.common.ArrayListObject;
import org.mfoyou.agent.utils.common.JsonRet;
import org.mfoyou.agent.utils.common.ListObject;
import org.mfoyou.agent.utils.common.MfoyouMap;
import org.mfoyou.agent.utils.json.Json2Object;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import java.io.IOException;
import java.text.ParseException;

@Controller
@Path("youzan")
public class YouZanController {

    private static final Logger logger = LoggerFactory.getLogger(YouZanController.class);

    @Autowired
    RedisCacheManger redisCacheManger;
    @Autowired
    YouzanService youzanService;
    @Autowired
    AccountService accountService;
    @Autowired
    SessionService sessionService;

    @GET
    @Path(value = "callback")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.ALLACCESS)
    public void callback(@Context HttpServletRequest request, @QueryParam("code") String code,
                         @QueryParam("state") Integer userId, @Context HttpServletResponse response) throws IOException {
        youzanService.getAccessToken(code, userId);
        response.sendRedirect("http://service.huawucloud.com/pages/marketing/thirdParty.html");
    }

    @GET
    @Path(value = "getcode")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.ALLACCESS)
    public void getcode(@Context HttpServletRequest request,
                        @Context HttpServletResponse response, @QueryParam("userId") Integer userId) throws Exception {
        if (userId == null) {
            response.getWriter().write("{\"state\":0,\"message\":\"参数缺失\"}");
        }
        String url = youzanService.getUrl(userId);
        response.sendRedirect(url);
    }

    /**
     * 接受订单消息推送
     *
     * @param request
     * @param json
     * @return
     * @throws ParseException
     */
    @POST
    @Path(value = "getPush")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.ALLACCESS)
    public String getPush(@Context HttpServletRequest request, String json) throws ParseException {
        youzanService.dealWithOrder(json);
        return "{\"code\":0,\"msg\":\"success\"}";
    }

    /**
     * 接受订单消息推送
     *
     * @param request
     * @param json
     * @return
     */
    @POST
    @Path(value = "addYouzanStoreInfo")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.AGENTACCESS)
    public JsonRet<?> addYouzanStoreInfo(@Context HttpServletRequest request, String json) {
        MfoyouMap mfoyouMap = Json2Object.json2MfoyouMap(json);
        String phone = mfoyouMap.get("account");
        if (phone == null) {
            return JsonRet.buildRet(-96);
        }
        Integer agentId = sessionService.currentUserId(request);
        HuawuUser userInfoByPhoneV1 = accountService.userInfoByPhoneV1(phone, agentId);
        if (userInfoByPhoneV1 == null) {
            return JsonRet.buildRet(-13);
        }
        HuawuYouzan huawuYouzan = new HuawuYouzan();
        huawuYouzan.setAgentId(agentId);
        huawuYouzan.setUserId(userInfoByPhoneV1.getUserId());
        huawuYouzan.setStoreLat(mfoyouMap.getDouble("lat"));
        huawuYouzan.setStoreLon(mfoyouMap.getDouble("lon"));
        huawuYouzan.setStoreAddress(mfoyouMap.get("address"));
        huawuYouzan.setStorePhone(mfoyouMap.get("phone"));
        huawuYouzan.setName(mfoyouMap.get("name"));
        huawuYouzan.setAccount(userInfoByPhoneV1.getUserPhone());
        huawuYouzan.setHeadPic(userInfoByPhoneV1.getUserHeadUrl());
        youzanService.addYouzanStore(huawuYouzan);
        return JsonRet.buildRet(0);
    }

    @GET
    @Path(value = "getYouzanStoreInfo")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.AGENTACCESS)
    public JsonRet<?> getYouzanStoreInfo(@Context HttpServletRequest request, @QueryParam("pageId") Integer pageId,
                                         @QueryParam("pageSize") Integer pageSize, @QueryParam("phone") String phone) {
        Integer userId = null;
        Integer agentId = null;
        if (phone != null) {
            agentId = sessionService.currentUserId(request);
            HuawuUser userInfoByPhoneV1 = accountService.userInfoByPhoneV1(phone, agentId);
            if (userInfoByPhoneV1 == null) {
                return JsonRet.buildRet(-96);
            }
            userId = userInfoByPhoneV1.getUserId();
        }
        ArrayListObject<?> storeInfos = youzanService.getStoreInfos(pageId, pageSize, userId, agentId);
        return JsonRet.buildSuccRet(ListObject.BulidListObject(storeInfos));
    }

    @POST
    @Path(value = "modifyYouzanStoreInfo")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.LOGINACCESS)
    public JsonRet<?> modifyYouzanStoreInfo(@Context HttpServletRequest request, String json) {
        logger.info(json);//后期做好权限校验
        HuawuYouzan huawuYouzan = JSON.parseObject(json, HuawuYouzan.class);
        int ret = youzanService.updateYouzan(huawuYouzan);
        return JsonRet.buildRet(ret - 1);
    }

}
